from time import sleep
import datetime
import sys
import joblib

#   配置
# user_dict = {'lanse': {'user': 'lanse', 'password': '123456', 'money': 0, 'phone': '13012341234'}}

err_num = 3


# 一级菜单退出
def quiit():
    sys.exit(0)


# 一级菜单，登录之前的菜单
def menu1(user):
    s_menu1 = '''
    ~~~~~~~~~ATM模拟系统~~~~~~~~~~用户：{}
    1、用户登录
    2、用户注册
    3、查看所有用户信息
    q、退出
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    '''.format(user)
    print(s_menu1)
    switch_d = {'1': check_login, '2': register, '3': load_alluser}
    while True:
        choice = input('请输入序号进行操作：')
        switch_d.get(choice, quiit)()


#   检查登录状态
def check_login():
    user_dict = joblib.load('data.pkl')
    user_key = user_dict.keys()

    c_user = input('请输入登录用户名：')
    c_password = input('请输入登录密码：')
    for i in range(0, err_num):
        if c_user in user_key:
            user_info = user_dict[c_user]
            user_info_user = user_info["user"]
            user_info_password = user_info["password"]
            if c_user == user_info_user and c_password == user_info_password:
                print(c_user, '登录成功')
                menu(c_user)
                break
            else:
                m = err_num - i
                if m == 0:
                    print(c_user, '登录失败3次，即将退出！')
                else:
                    print("{}登录失败，剩余{}次机会,请检查用户名和密码！".format(c_user, str(m)))

        else:
            print(c_user, '尚未注册！请进行注册')
            break


#   用户注册
def register():
    r_user = input('请输入注册用户名：')
    user_dict = joblib.load('data.pkl')
    user_key = user_dict.keys()
    if r_user not in user_key:
        info_dict = {}
        r_password = input('请输入注册密码：')
        r_phone = input('请输入注册手机号：')
        info_dict['user'] = r_user
        info_dict['password'] = r_password
        info_dict['phone'] = r_phone
        info_dict['money'] = 5000
        user_dict[r_user] = info_dict
        user_key1 = user_dict.keys()
        if r_user in user_key1:
            print(r_user, '注册成功！')
            joblib.dump(user_dict, 'data.pkl')

        else:
            print(r_user, '注册失败！')
        menu1(user)
    else:
        print(r_user, '已存在！')


#   查看用户所有信息
def load_alluser():
    all_info = joblib.load('data.pkl')
    print('~~~~~~~~~~~~~~~~~~~~~~~~')
    print('用户所有信息:')
    for k, v in all_info.items():
        print(k, ">>", v)
    print('~~~~~~~~~~~~~~~~~~~~~~~~')
    print('')
    menu1(user)


#   返回上一级
def ret(user):
    while True:
        print('~~~~~~~~~~~~~~~~~~~~~~~~')
        choice = input("请输入q返回上一级:")
        if choice == 'q':
            while True:
                menu(user)
        else:
            print("请重新输入!")


# 查看账户余额
def show_money(user):
    user_dict = joblib.load('data.pkl')
    money = user_dict[user]['money']
    print("{}查看账户余额为：{}".format(user, money))
    ret(user)


# 转账
def trans(user):
    user_dict = joblib.load('data.pkl')
    money = user_dict[user]['money']
    print("{}转账之前余额为：{}".format(user, money))
    print('~~~~~~~~~~~~~~~~~~~~~~~~')
    user2 = input('请输入转入方用户名：')
    trans_money = int(input('请输入交易金额：'))
    user_key1 = user_dict.keys()
    if user2 in user_key1:
        # 判断转出金额小于等于余额
        if trans_money <= money:
            # 转出方更新余额
            s_money = money - trans_money
            user_dict[user]['money'] = s_money
            # 转入方更新余额
            in_money = user_dict[user2]['money']
            z_money = in_money + trans_money
            user_dict[user2]['money'] = z_money
            joblib.dump(user_dict, 'data.pkl')
            print('转账成功')
            # 交易时间
            now_time = datetime.datetime.now().strftime('%Y-%m-%d  %H:%M:%S')
            sleep(1)
            print('~~~~~~~~~~交易明细~~~~~~~~~~~~~~')
            print('转出方:', user)
            print('转入方:', user2)
            print('交易金额:', trans_money)
            print('交易时间:', now_time)
        else:
            print('转账失败，金额不足')

    else:
        print("转账失败，转入方用户名{}不存在".format(user2))
    ret(user)


# 存钱
def add_money(user):
    user_dict = joblib.load('data.pkl')
    a_money = int(input('请输入存入金额(100的倍数)：'))
    money = user_dict[user]['money']
    u_money = money + a_money
    user_dict[user]['money'] = u_money
    print("{}存款之后余额为：{}".format(user, u_money))
    joblib.dump(user_dict, 'data.pkl')
    ret(user)


# 取款
def del_money(user):
    user_dict = joblib.load('data.pkl')
    a_money = int(input('请输入取出金额(100的倍数)：'))
    money = user_dict[user]['money']
    if a_money <= money:
        u_money = money - a_money
        user_dict[user]['money'] = u_money
        print("{}取款之后余额为：{}".format(user, u_money))
        joblib.dump(user_dict, 'data.pkl')
    else:
        print(user, '取款之后余额不足！')
    ret(user)


def quit1(user):
    pass

# 二级菜单，用户登录成功的菜单


def menu(userid):
    s_menu = '''
    ~~~~~~~~~ATM模拟系统~~~~~~~~~~用户：{}
    1、账户余额
    2、转账
    3、存钱
    4、取款
    q、退出
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    '''.format(userid)
    print(s_menu)
    switch_d = {'1': show_money, '2': trans, '3': add_money, '4': del_money}
    while True:
        choice = input('请输入序号进行操作：')
        switch_d.get(choice, menu1)(userid)


if __name__ == '__main__':
    user = 'XXXX'
    while True:
        menu1(user)

# 不需要其它的库，主要考察的是对基础知识的掌握
